﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using CoyoEden;
using System.Collections.Specialized;
using System.Text;
using System.Collections.Generic;
using CoyoEden.Models;

public partial class widgets_CategoryNewPosts_edit : WidgetEditBase
{
	#region base impementation
	public override void Save() {
		StringDictionary settings = GetSettings();
		StringBuilder selectedCategory = new StringBuilder();
		foreach (ListItem c in rbtnCategory.Items)
		{
			if (c.Selected == true) {
				selectedCategory.Append(c.Value);
				break;
			}
		}
		settings["clist"] = selectedCategory.ToString();
		settings["showNum"] = this.txtPostsDisplayNum.Text;
		SaveSettings(settings);
	}
	protected override void OnPreRender(EventArgs e) {
		if (!Page.IsPostBack) {
			//load current settings
			StringDictionary settings = GetSettings();
			string selectedCategory = null;
			if (settings.ContainsKey("clist")) {
				selectedCategory = settings["clist"];
			}
			//bind categories
			rbtnCategory.DataValueField = "Id";
			rbtnCategory.DataTextField = "Title";
			rbtnCategory.DataSource = CategoryList;
			rbtnCategory.DataBind();
			//reset selected categories
			if (!string.IsNullOrEmpty(selectedCategory))
			{
				ListItem tempItem = null;
				tempItem = rbtnCategory.Items.FindByValue(selectedCategory);
				if (tempItem != null) {
					tempItem.Selected = true;
				}
			}
			//Assign posts' display number
			this.txtPostsDisplayNum.Text = settings.ContainsKey("showNum") ? settings["showNum"] : "7";
		}
		base.OnPreRender(e);
	}
	#endregion

	#region private fields
	private static readonly string CATEGORIESCACHEKEY = "CategoryListForMenu";
	private static List<Category> _CategoryList;
	private static object _SyncRoot = new object();
	private static List<Category> CategoryList {
		get {
			_CategoryList = HttpRuntime.Cache[CATEGORIESCACHEKEY] as List<Category>;
			if (_CategoryList == null) {
				lock (_SyncRoot) {
					if (null == _CategoryList) {
						_CategoryList = Category.TopCategories;
						HttpRuntime.Cache.Insert(CATEGORIESCACHEKEY, _CategoryList);
					}
				}
			}
			return _CategoryList;
		}
	}
	#endregion

	#region Category.Saved event subscribing
	static widgets_CategoryNewPosts_edit()
	{
		Category.Saved += new EventHandler<SavedEventArgs>(Category_Saved);
	}

	static void Category_Saved(object sender, SavedEventArgs e) {
		HttpRuntime.Cache.Remove(CATEGORIESCACHEKEY);
	}
	#endregion
}
